package cn.dida.service.impl;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.dida.dao.CompanyDao;
import cn.dida.dao.SalesmanDao;
import cn.dida.exception.BizzException;
import cn.dida.model.Company;
import cn.dida.model.EntPayEntity;
import cn.dida.model.Pageable;
import cn.dida.model.RedPackEntity;
import cn.dida.model.SalesNewMan;
import cn.dida.model.Salesman;
import cn.dida.model.SalesmanSaleHistory;
import cn.dida.service.SalesmanService;
import cn.dida.util.AliyunMqUtil;
import cn.dida.weixin.qyh.ErrorCodeMapping;
import cn.dida.weixin.qyh.QyhApiClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
 * 促销员管理 接口实现类
 * @author weiwei
 *
 */
@Service
public class SalesmanServiceImpl implements SalesmanService {
    @Autowired
    private SalesmanDao salesmanDao;
    @Autowired
    private CompanyDao companyDao;

    @Override
    public Pageable<SalesNewMan> querySalesman(Integer companyId, String keyword,String branchkeyword, String adname,  Integer state, int page) {
        return salesmanDao.query(companyId, keyword,branchkeyword, adname,state, page);
    }

    @Override
    public List<Salesman> querySalesman(Integer companyId, Integer state) {
        return salesmanDao.query(companyId, state);
    }
    @Transactional
    @Override
    public Boolean insertSalesman(Salesman salesman) {
        //录入微信企业号通讯录
        Company company = companyDao.get(salesman.getCompanyId());

        JSONObject preference = JSONObject.parseObject(company.getPreference());
        String corpid = preference.getString("weixin_qyh_corpid");
        String corpsecret = preference.getString("weixin_qyh_corpsecret");
        QyhApiClient qyhApiClient = new QyhApiClient(corpid, corpsecret);

        JSONObject re = qyhApiClient.createUser(salesman.getPhone(), salesman.getName(), salesman.getDepartmentId(), salesman.getPhone());
        System.out.println("createUser:" + re);
        if (re.getInteger("errcode") == 0) {
            return salesmanDao.insert(salesman) == 1;
        } else {
            throw new BizzException(BizzException.error_code_invalid_request, ErrorCodeMapping.getMsgByCode(re.getInteger("errcode")));
        }
    }
    @Transactional
    @Override
    public Boolean updateSalesman(SalesNewMan salesman) {
        //更新微信企业号通讯录
        Company company = companyDao.get(salesman.getCompanyId());

//        JSONObject preference = JSONObject.parseObject(company.getPreference());
//        String corpid = preference.getString("weixin_qyh_corpid");
//        String corpsecret = preference.getString("weixin_qyh_corpsecret");
//        QyhApiClient qyhApiClient = new QyhApiClient(corpid, corpsecret);
//
//        JSONObject re = qyhApiClient.updateUser(salesman.getPhone(), salesman.getName(), salesman.getDepartmentId(), salesman.getPhone());
//        if (re.getInteger("errcode") == 0) {
        	Integer result = salesmanDao.update(salesman);
        	if(result == 1){
        		result = salesmanDao.updatebranch(salesman);
        	}
            return result == 1;
//        } else {
//            throw new BizzException(BizzException.error_code_invalid_request, ErrorCodeMapping.getMsgByCode(re.getInteger("errcode")));
//        }
    }

    @Override
    public SalesNewMan getSalesman(Integer companyId, Integer id) {
        return salesmanDao.get(companyId, id);
    }

    @Override
    public Salesman getSalesmanByPhone(Integer companyId, String phone) {
        return salesmanDao.getByMobile(companyId, phone);
    }

    @Transactional
    @Override
    public Boolean deleteSalesman(Integer companyId, Integer id) {
        //删除微信企业号通讯录
        Company company = companyDao.get(companyId);
        JSONObject preference = JSONObject.parseObject(company.getPreference());
        String corpid = preference.getString("weixin_qyh_corpid");
        String corpsecret = preference.getString("weixin_qyh_corpsecret");
        QyhApiClient qyhApiClient = new QyhApiClient(corpid, corpsecret);

        SalesNewMan salesman = salesmanDao.get(companyId, id);
        if (salesman == null) {
            return true;
        }

        JSONObject re = qyhApiClient.deleteUser(salesman.getPhone());
        if (re.getInteger("errcode") == 0) {
            return salesmanDao.delete(companyId, id) == 1;
        } else {
            throw new BizzException(BizzException.error_code_invalid_request, ErrorCodeMapping.getMsgByCode(re.getInteger("errcode")));
        }
    }

    @Override
    public Pageable<SalesmanSaleHistory> querySaleHistory(Integer salesmanId, String keyword, Long timeLimitStart, Long timeLimitEnd, int page) {
        return salesmanDao.querySaleHistory(salesmanId, keyword, timeLimitStart, timeLimitEnd, page);
    }

    @Override
    public List<SalesNewMan> querySalesmanForExport(Integer companyId,String keyword, String branchkeyword, String adname, Integer state) {
        // TODO Auto-generated method stub
        return salesmanDao.queryForExport(companyId, keyword, branchkeyword, adname, state);
    }

    @Override
    public List<SalesmanSaleHistory> querySaleHistoryForExport(
            Integer salesmanId, String keyword, Long timeLimitStart,
            Long timeLimitEnd) {
        // TODO Auto-generated method stub
        return salesmanDao.querySaleHistoryForExport(salesmanId, keyword, timeLimitStart, timeLimitEnd);
    }
    
    @Override
    public Pageable<Map<String,Object>> querysalepaymentyList(Integer companyid, String keyword, 
    		Long timeLimitStart, Long timeLimitEnd, int page){
    	 // TODO Auto-generated method stub
    	return salesmanDao.querysalepaymentyList(companyid, keyword, timeLimitStart, timeLimitEnd, page);
    }
    @Override
    public Pageable<Map<String, Object>> querysalepaymentydetailList(Integer companyid, String keyword, String companyname, String price, Integer product_id,Integer page){
    	// TODO Auto-generated method stub
    	return salesmanDao.querysalepaymentydetailList(companyid, keyword,companyname,price, product_id,page);
    }
    
    @Transactional
    @Override
    public Boolean PaymentlistSave(JSONArray js,String product_id ){
    	// TODO Auto-generated method stub
    	JSONArray newjs = new JSONArray();
    	long newtime = Calendar.getInstance().getTimeInMillis();
    	if(js!=null && js.size()>0){
    		Integer salesman_id = null;
    		float price = 0;
    		DecimalFormat fnum  = new  DecimalFormat("##0.00");
        	for(Object jo :js){
        		JSONObject genjo= JSONObject.parseObject(jo.toString());
        		
        		price = genjo.getFloat("price");
        		Company company = companyDao.get(genjo.getInteger("company_id"));
                JSONObject preference = JSONObject.parseObject(company.getPreference());
                String weixin_qyhmh_id = preference.getString("weixin_qyhmh_id");
                String weixin_qyhmh_pay_key = preference.getString("weixin_qyhmh_pay_key");
                Integer sumprice = (int) (Float.parseFloat(genjo.getString("sumprice"))*10*10);
                RedPackEntity redpack=new RedPackEntity();
                redpack.setCallBackUrl(ResourceBundle.getBundle("app").getString("aliyun.mq.callbackaddr")+"callback");
	            redpack.setMchId(weixin_qyhmh_id);
	            redpack.setMchKey(weixin_qyhmh_pay_key);
	            redpack.setAppId(genjo.getString("appid"));
	            redpack.setReOpenid(genjo.getString("openid"));
	            redpack.setClientIp(ResourceBundle.getBundle("app").getString("runtime.ip"));
	            redpack.setTotalAmount(sumprice);
	            redpack.setActName("扫码返利活动");
	            redpack.setSendName(preference.getString("weixin_gzh_name"));
	            redpack.setTotalNum(1);
	            redpack.setRemark("扫码返利");
	            redpack.setWishing("恭喜发财");
	            redpack.setSceneId("PRODUCT_2");
	            String message_id=AliyunMqUtil.sendRedPackPayMessage(redpack);
                genjo.put("message_id", message_id);
//                System.out.println(AliyunMqUtil.sendEntPayMessage(entPay));
                newjs.add(genjo);
                salesman_id = genjo.getInteger("salesman_id");
                String tableid = genjo.getString("tableid");
                Float newprice = Float.parseFloat(fnum.format(price));
                //更新log_scancode_salesman 表的payment_state =1 支付中
                salesmanDao.updatelogscancodesalesmanstate(salesman_id, product_id,newtime,newprice,tableid);
        	}
        	
        	//更新log_scancode_salesman 表的payment_state =1 支付中
        	//if(product_id.length()>0 && salesman_id.length()>0){
        		//salesmanDao.updatelogscancodesalesmanstate("("+salesman_id +")", product_id,newtime,price);
        	//}
        	//向log_scancode_salepayment表插入数据
        	salesmanDao.inerstlogscancodesalesmanpayment(newjs,newtime);
        	
    	}
    	
    	return null;
    }

    @Override
    public Pageable<Map<String, Object>> querysalepayoffmentyList(Integer companyId, String keyword, Long timeLimitStart,
			Long timeLimitEnd, Integer page){
    	// TODO Auto-generated method stub
    	return salesmanDao.querysalepaymentyoffList(companyId, keyword, timeLimitStart, timeLimitEnd, page);
    }
    
    @Override
    public Pageable<Map<String, Object>> querysalepaymentyoffdetailList(Integer companyId, String keyword, String companyname,
			Integer product_id, String c_time ,Integer page){
    	// TODO Auto-generated method stub
    	return salesmanDao.querysalepaymentyoffdetailList(companyId, keyword,companyname,product_id,c_time,page);
    }
    
    @Transactional
    @Override
    public Boolean updatePaymentState(JSONObject jo) {
        //更新状态    	
    	boolean result =false;
    	boolean resultSalesman = false;
    	if(jo.containsKey("message_id")&&jo.containsKey("pay_result")){
    		String message_id = jo.getString("message_id");
    		int pay_result = jo.getInteger("pay_result");
    		String descripe = jo.getString("descripe");
    		
    		result = salesmanDao.updatSalesmanOffPaymentState(message_id,descripe,pay_result);
    		Map<String, Object> resultmap = salesmanDao.queryMessageidtoSalesmanIdAndProductId(message_id);
    		if(resultmap!=null){
    			Integer salesmanid=(Integer) resultmap.get("salesman_id");
    			Integer productid = (Integer) resultmap.get("product_id");
    			Long playmenttime = (Long) resultmap.get("c_time");
    			resultSalesman = salesmanDao.updatSalesmanPaymentState(salesmanid,productid,playmenttime,pay_result);
    		}
    		
    	}
    	return result&&resultSalesman;
    }
    
    @Override
    public List<Map<String, Object>> querySalepaymentyExport(
            Integer companyId, String keyword, Long timeLimitStart,
            Long timeLimitEnd) {
        // TODO Auto-generated method stub
        return salesmanDao.querySalepaymentyExport(companyId, keyword, timeLimitStart, timeLimitEnd);
    }
    
    @Override
    public List<Map<String, Object>> querySalepaymentOffExport(
            Integer companyId, String keyword, Long timeLimitStart,
            Long timeLimitEnd) {
        // TODO Auto-generated method stub
        return salesmanDao.querySalepaymentOffExport(companyId, keyword, timeLimitStart, timeLimitEnd);
    }
    
    
}
